<template>
  <div class="file-explorer">
    <div class="explorer-header">
      <div class="action-bar">
        <!-- 视图切换 -->
        <div class="view-toggle">
          <el-radio-group v-model="viewMode" size="small" class="view-radio">
            <el-radio-button label="grid">
              <el-icon><Grid /></el-icon>
              网格视图
            </el-radio-button>
            <el-radio-button label="list">
              <el-icon><Menu /></el-icon>
              列表视图
            </el-radio-button>
          </el-radio-group>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-tooltip content="刷新" placement="top">
            <el-button 
              type="primary" 
              :icon="Refresh" 
              circle 
              @click="refreshFiles"
              class="action-btn"
              :loading="loading"
            />
          </el-tooltip>
          
          <el-tooltip content="上传文件" placement="top" v-if="canUpload">
            <el-button 
              type="success" 
              :icon="Upload" 
              circle 
              @click="showUploadDialog"
              class="action-btn"
            />
          </el-tooltip>
          
          <el-tooltip content="新建文件夹" placement="top" v-if="canCreateFolder">
            <el-button 
              type="info" 
              :icon="FolderAdd" 
              circle 
              @click="showCreateFolderDialog"
              class="action-btn"
            />
          </el-tooltip>
        </div>
      </div>
      
      <!-- 搜索过滤区域 -->
      <div class="search-filter">
        <el-input
          v-model="searchQuery"
          placeholder="搜索文件..."
          class="search-input"
          clearable
          @clear="debouncedSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
          <template #append>
            <el-dropdown trigger="click" @command="handleSearchCommand">
              <el-button type="primary">
                高级
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="search-name">按名称搜索</el-dropdown-item>
                  <el-dropdown-item command="search-content" :disabled="true">按内容搜索</el-dropdown-item>
                  <el-dropdown-item command="search-date" :disabled="true">按日期搜索</el-dropdown-item>
                  <el-dropdown-item divided command="clear-search">清除搜索</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-input>
        
        <el-select v-model="categoryFilter" placeholder="按类别筛选" class="filter-select" @change="debouncedSearch">
          <el-option label="全部" value="" />
          <el-option v-for="category in categories" :key="category" :label="category" :value="category" />
        </el-select>
        
        <el-select v-model="typeFilter" placeholder="按类型筛选" class="filter-select" @change="debouncedSearch">
          <el-option label="全部" value="" />
          <el-option label="文件夹" value="directory" />
          <el-option label="文档" value="document" />
          <el-option label="图片" value="image" />
          <el-option label="视频" value="video" />
          <el-option label="音频" value="audio" />
          <el-option label="压缩包" value="archive" />
        </el-select>
      </div>
      
      <!-- 面包屑导航 -->
      <div class="breadcrumb-nav">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '' }" @click="navigateTo('')">
            <div class="breadcrumb-item">
              <FileTypeIcon fileType="directory" size="small" />
              <span>根目录</span>
            </div>
          </el-breadcrumb-item>
          <template v-for="(part, index) in breadcrumbParts" :key="index">
            <el-breadcrumb-item 
              :to="{ path: part.path }" 
              @click="navigateTo(part.path)"
            >
              <div class="breadcrumb-item">
                <FileTypeIcon fileType="directory" size="small" />
                <span>{{ part.name }}</span>
              </div>
            </el-breadcrumb-item>
          </template>
        </el-breadcrumb>
      </div>
    </div>
    
    <div class="explorer-body">
      <!-- 加载状态 -->
      <div v-if="loading && !files.length" class="loading-container">
        <el-skeleton :rows="10" animated />
      </div>
      
      <!-- 空状态 -->
      <el-empty
        v-if="!loading && (!files || files.length === 0)"
        description="没有找到文件"
        class="empty-state"
      />
      
      <!-- 网格视图模式 -->
      <div v-else-if="viewMode === 'grid'" class="grid-view">
        <FileCard
          v-for="file in filteredFiles"
          :key="file.id"
          :file="file"
          :can-delete="canDelete"
          :is-selected="selectedFile && selectedFile.id === file.id"
          @click="handleFileClick(file)"
          @dblclick="handleFileDblClick(file)"
          @preview="previewFile"
          @download="downloadFile"
          @open="openFileInReader"
          @info="showFileInfo"
          @delete="confirmDeleteFile"
        />
      </div>
      
      <!-- 列表视图模式 -->
      <div v-else class="list-view">
        <FileList
          :files="filteredFiles"
          :loading="loading"
          :can-delete="canDelete"
          :selected-file="selectedFile"
          @row-click="handleFileClick"
          @preview="previewFile"
          @download="downloadFile"
          @open="openFileInReader"
          @info="showFileInfo"
          @delete="confirmDeleteFile"
        />
      </div>
    </div>
    
    <!-- 文件预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      :title="selectedFile?.name || '文件预览'"
      :width="isMobile ? '95%' : '80%'"
      destroy-on-close
      top="5vh"
    >
      <div class="preview-dialog-content" v-if="selectedFile">
        <DocumentViewer
          :document-url="selectedFile.url"
          :document-name="selectedFile.name"
          :document-type="getDocumentType(selectedFile)"
        />
      </div>
    </el-dialog>
    
    <!-- 文件信息对话框 -->
    <el-dialog
      v-model="fileInfoDialogVisible"
      title="文件信息"
      :width="isMobile ? '95%' : '500px'"
      destroy-on-close
    >
      <div class="file-info-content" v-if="selectedFile">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="文件名">{{ selectedFile.name }}</el-descriptions-item>
          <el-descriptions-item label="类型">{{ getFileTypeLabel(selectedFile.type) }}</el-descriptions-item>
          <el-descriptions-item label="大小">{{ selectedFile.size }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ selectedFile.updateTime }}</el-descriptions-item>
          <el-descriptions-item label="分类">{{ selectedFile.category }}</el-descriptions-item>
          <el-descriptions-item label="路径" v-if="selectedFile.key">{{ selectedFile.key }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="file-info-actions">
          <el-button 
            v-if="selectedFile.type !== 'directory' && isDocumentFile(selectedFile)"
            type="primary" 
            @click="openFileInReader(selectedFile); fileInfoDialogVisible = false"
          >
            在阅读器中打开
          </el-button>
          
          <el-button 
            v-if="selectedFile.type !== 'directory'"
            type="success" 
            @click="downloadFile(selectedFile)"
          >
            下载文件
          </el-button>
        </div>
      </div>
    </el-dialog>
    
    <!-- 创建文件夹对话框 -->
    <el-dialog
      v-model="createFolderDialogVisible"
      title="新建文件夹"
      :width="isMobile ? '95%' : '400px'"
      destroy-on-close
    >
      <el-form :model="folderForm" label-width="80px">
        <el-form-item label="文件夹名">
          <el-input v-model="folderForm.name" placeholder="请输入文件夹名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createFolderDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createFolder" :loading="creatingFolder">
            创建
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 上传文件对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传文件"
      :width="isMobile ? '95%' : '500px'"
      destroy-on-close
    >
      <el-upload
        class="upload-area"
        drag
        action="#"
        :auto-upload="false"
        :on-change="handleFileChange"
        :file-list="uploadFiles"
        multiple
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖拽文件到此处或 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            上传到当前目录: {{ currentPath || '根目录' }}
          </div>
        </template>
      </el-upload>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="uploadSelectedFiles" :loading="uploading" :disabled="!uploadFiles.length">
            上传
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { useMainStore, useFilePreviewStore, usePermissionStore } from '../../store';
import { 
  Search, Folder, FolderAdd, Document, Grid, Menu, 
  Refresh, Upload, UploadFilled, ArrowDown
} from '@element-plus/icons-vue';
import cosFileService from '../../services/CosFileService';
import FileCard from './FileCard.vue';
import FileList from './FileList.vue';
import FileTypeIcon from './FileTypeIcon.vue';
import DocumentViewer from './DocumentViewer.vue';

const props = defineProps({
  // 是否使用COS服务，如果为false则使用传入的files
  useCosService: {
    type: Boolean,
    default: false
  },
  // COS服务配置
  cosConfig: {
    type: Object,
    default: () => ({})
  },
  // 文件列表，当useCosService为false时使用
  files: {
    type: Array,
    default: () => []
  },
  // 是否正在加载
  loading: {
    type: Boolean,
    default: false
  },
  // 是否可以预览文件
  previewInDialog: {
    type: Boolean,
    default: true
  },
  // 是否可以上传文件
  canUpload: {
    type: Boolean,
    default: false
  },
  // 是否可以创建文件夹
  canCreateFolder: {
    type: Boolean,
    default: false
  },
  // 是否可以删除文件
  canDelete: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits([
  'file-read', 
  'file-download', 
  'file-preview', 
  'refresh',
  'file-upload',
  'folder-create',
  'file-delete'
]);

// 获取store和router
const store = useMainStore();
const filePreviewStore = useFilePreviewStore();
const permissionStore = usePermissionStore();
const router = useRouter();

// 状态管理
const searchQuery = ref('');
const categoryFilter = ref('');
const typeFilter = ref('');
const viewMode = ref('grid'); // 默认网格视图
const previewDialogVisible = ref(false);
const fileInfoDialogVisible = ref(false);
const createFolderDialogVisible = ref(false);
const uploadDialogVisible = ref(false);
const selectedFile = ref(null);
const currentPath = ref('');
const internalFiles = ref([]);
const internalLoading = ref(false);
const creatingFolder = ref(false);
const folderForm = ref({ name: '' });
const uploadFiles = ref([]);
const uploading = ref(false);

// 面包屑导航
const breadcrumbParts = computed(() => {
  if (!currentPath.value) return [];
  
  // 分割路径并过滤空字符串
  const parts = currentPath.value.split('/').filter(Boolean);
  console.log('面包屑导航路径处理:', { 当前路径: currentPath.value, 分割后: parts });
  
  // 构建面包屑导航项
  return parts.map((part, index) => {
    // 构建到当前部分的路径
    const path = parts.slice(0, index + 1).join('/');
    console.log(`构建面包屑项 #${index}:`, { 名称: part, 路径: path });
    return { name: part, path };
  });
});

// 检测是否为移动设备
const isMobile = computed(() => {
  return window.innerWidth <= 768;
});

// 计算所有分类
const categories = computed(() => {
  const categorySet = new Set();
  
  const extractCategories = (items) => {
    items.forEach(item => {
      if (item.category) categorySet.add(item.category);
      if (item.children) extractCategories(item.children);
    });
  };
  
  extractCategories(getDisplayFiles.value);
  return Array.from(categorySet);
});

// 获取显示的文件列表
const getDisplayFiles = computed(() => {
  return props.useCosService ? internalFiles.value : props.files;
});

// 过滤文件
const filteredFiles = computed(() => {
  let files = getDisplayFiles.value;
  
  if (!searchQuery.value && !categoryFilter.value && !typeFilter.value) {
    return files;
  }
  
  return files.filter(file => {
    const nameMatch = file.name.toLowerCase().includes(searchQuery.value.toLowerCase());
    const categoryMatch = !categoryFilter.value || file.category === categoryFilter.value;
    const typeMatch = !typeFilter.value || file.type === typeFilter.value;
    return nameMatch && categoryMatch && typeMatch;
  });
});

// 搜索处理
const handleSearch = () => {
  // 实现搜索逻辑
  console.log('执行搜索:', { 
    查询: searchQuery.value, 
    分类: categoryFilter.value,
    类型: typeFilter.value,
    结果数量: filteredFiles.value.length 
  });
  
  // 如果搜索结果为空，显示提示
  if (filteredFiles.value.length === 0 && (searchQuery.value || categoryFilter.value || typeFilter.value)) {
    ElMessage({
      type: 'info',
      message: `未找到匹配的文件${categoryFilter.value ? `（分类：${categoryFilter.value}）` : ''}${typeFilter.value ? `（类型：${typeFilter.value}）` : ''}`,
      duration: 2000
    });
  }
  
  // 如果搜索结果只有一个文件，可以自动选中
  if (filteredFiles.value.length === 1 && searchQuery.value) {
    // 高亮显示但不自动打开，避免干扰用户
    selectedFile.value = filteredFiles.value[0];
  }
};

// 添加防抖处理，避免频繁搜索
const debounce = (fn, delay) => {
  let timer = null;
  return function(...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

// 使用防抖处理的搜索函数
const debouncedSearch = debounce(handleSearch, 300);

// 监听搜索条件变化
watch([searchQuery, categoryFilter, typeFilter], () => {
  debouncedSearch();
});

// 判断是否为文档文件
const isDocumentFile = (file) => {
  const extension = file.name.split('.').pop().toLowerCase();
  
  // 扩展支持的文档类型
  const documentExtensions = [
    'pdf', 'docx', 'doc', 'md', 'markdown', 
    'html', 'htm', 'txt', 'text', 'log', 
    'json', 'xml', 'csv', 'rtf', 'ppt', 'pptx',
    'xls', 'xlsx'
  ];
  
  return documentExtensions.includes(extension) || 
         ['document', 'markdown', 'text', 'html', 'presentation', 'spreadsheet'].includes(file.type);
};

// 获取文档类型
const getDocumentType = (file) => {
  // 首先检查文件的类型属性
  if (file.type === 'markdown' || file.type === 'md') {
    return 'markdown';
  } else if (file.type === 'html') {
    return 'html';
  } else if (file.type === 'presentation' || file.type === 'powerpoint') {
    return 'presentation';
  } else if (file.type === 'spreadsheet' || file.type === 'excel') {
    return 'spreadsheet';
  } else if (file.type === 'pdf') {
      return 'pdf';
  } else if (file.type === 'word') {
      return 'word';
  }
  
  // 如果文件类型不明确，通过扩展名判断
  const extension = file.name.split('.').pop().toLowerCase();
  
  // 根据扩展名判断
  if (['md', 'markdown'].includes(extension)) {
    return 'markdown';
    } else if (['html', 'htm'].includes(extension)) {
      return 'html';
  } else if (['ppt', 'pptx'].includes(extension)) {
    return 'presentation';
  } else if (['xls', 'xlsx'].includes(extension)) {
    return 'spreadsheet';
  } else if (extension === 'pdf') {
    return 'pdf';
  } else if (['doc', 'docx'].includes(extension)) {
    return 'word';
    } else if (['txt', 'text', 'log', 'json', 'xml', 'csv'].includes(extension)) {
      return 'text';
    }
  
  // 如果是document类型但没有具体扩展名，尝试进一步判断
  if (file.type === 'document') {
    // 根据文件名判断类型
    if (file.name.toLowerCase().endsWith('.pdf')) {
      return 'pdf';
    } else if (file.name.toLowerCase().endsWith('.doc') || file.name.toLowerCase().endsWith('.docx')) {
      return 'word';
    } else if (file.name.toLowerCase().endsWith('.ppt') || file.name.toLowerCase().endsWith('.pptx')) {
      return 'presentation';
    } else if (file.name.toLowerCase().endsWith('.xls') || file.name.toLowerCase().endsWith('.xlsx')) {
      return 'spreadsheet';
    }
  }
  
  // 默认返回自动类型
  return 'auto';
};

// 获取文件类型标签
const getFileTypeLabel = (type) => {
  const typeMap = {
    'directory': '文件夹',
    'document': '文档',
    'markdown': 'Markdown',
    'image': '图片',
    'video': '视频',
    'audio': '音频',
    'archive': '压缩包',
    'other': '其他'
  };
  
  return typeMap[type] || '未知';
};

// 处理文件点击
const handleFileClick = (file) => {
  // 如果是目录，导航到该目录
  if (file.type === 'directory') {
    // 修复：确保不会出现多余的斜杠
    let path;
    if (file.prefix) {
      // 从前缀中提取路径，确保移除COS前缀和多余斜杠
      path = file.prefix.replace(cosFileService.config.Prefix, '').replace(/\/+$/, '');
      console.log('从前缀提取路径:', {
        原始前缀: file.prefix,
        COS前缀: cosFileService.config.Prefix,
        处理后路径: path
      });
    } else {
      // 构建路径，确保不会有多余斜杠
      path = currentPath.value ? `${currentPath.value}/${file.name}` : file.name;
      console.log('构建新路径:', {
        当前路径: currentPath.value,
        文件夹名: file.name,
        处理后路径: path
      });
    }
    navigateTo(path);
  }
};

// 处理文件双击
const handleFileDblClick = (file) => {
  // 如果是目录，导航到该目录
  if (file.type === 'directory') {
    // 修复：确保不会出现多余的斜杠
    let path;
    if (file.prefix) {
      // 从前缀中提取路径，确保移除COS前缀和多余斜杠
      path = file.prefix.replace(cosFileService.config.Prefix, '').replace(/\/+$/, '');
    } else {
      // 构建路径，确保不会有多余斜杠
      path = currentPath.value ? `${currentPath.value}/${file.name}` : file.name;
    }
    navigateTo(path);
  } else if (isDocumentFile(file)) {
    // 如果是文档文件，在阅读器中打开
    openFileInReader(file);
  } else {
    // 其他文件预览
    previewFile(file);
  }
};

// 导航到指定路径
const navigateTo = async (path) => {
  if (!props.useCosService) return;
  
  currentPath.value = path;
  await loadFilesFromCos();
};

// 从COS加载文件
const loadFilesFromCos = async () => {
  if (!props.useCosService || !cosFileService.isInitialized) {
    console.error('COS服务未初始化，无法加载文件');
    ElMessage.warning('COS服务未初始化，无法加载文件');
    return;
  }
  
  internalLoading.value = true;
  
  try {
    console.log('开始从COS加载文件，当前路径:', currentPath.value);
    const result = await cosFileService.listFiles(currentPath.value);
    console.log('COS返回结果:', result);
    
    if (result.directories.length === 0 && result.files.length === 0) {
      console.warn('COS返回空内容，可能路径配置有误或权限不足');
      ElMessage.warning(`目录 ${currentPath.value || '根目录'} 为空或无访问权限`);
    }
    
    internalFiles.value = [...result.directories, ...result.files];
  } catch (error) {
    console.error('加载文件失败:', error);
    ElMessage.error('加载文件失败: ' + (error.message || '未知错误'));
    internalFiles.value = [];
  } finally {
    internalLoading.value = false;
  }
};

// 刷新文件列表
const refreshFiles = async () => {
  if (props.useCosService) {
    await loadFilesFromCos();
  } else {
    emit('refresh');
  }
};

// 预览文件
const previewFile = (file) => {
  selectedFile.value = file;
  previewDialogVisible.value = true;
};

// 在阅读器中打开文件
const openFileInReader = (file) => {
  // 使用Pinia store保存文件信息
  filePreviewStore.setFile(file);
  
  // 发送事件
  emit('file-read', file);
  
  // 关闭文件浏览器对话框
  if (previewDialogVisible.value) {
    previewDialogVisible.value = false;
  }
  
  // 导航到文件阅读器页面
  router.push('/file-reader');
};

// 下载文件
const downloadFile = (file) => {
  // 检查下载权限
  if (!permissionStore.canDownload) {
    ElMessage.warning(permissionStore.downloadDisabledMessage);
    return;
  }
  
  if (props.useCosService) {
    cosFileService.downloadFile(file.key, file.name);
  } else {
  emit('file-download', file);
  
  try {
    const link = document.createElement('a');
    link.href = file.url;
    link.download = file.name;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
      ElMessage.success('文件下载已开始');
  } catch (err) {
    console.error('下载文件失败:', err);
      ElMessage.error('下载文件失败，请重试');
    }
  }
};

// 显示文件信息
const showFileInfo = (file) => {
  selectedFile.value = file;
  fileInfoDialogVisible.value = true;
};

// 显示创建文件夹对话框
const showCreateFolderDialog = () => {
  folderForm.value.name = '';
  createFolderDialogVisible.value = true;
};

// 创建文件夹
const createFolder = async () => {
  if (!folderForm.value.name) {
    ElMessage.warning('请输入文件夹名称');
    return;
  }
  
  creatingFolder.value = true;
  
  try {
    if (props.useCosService) {
      await cosFileService.createFolder(folderForm.value.name, currentPath.value);
      ElMessage.success(`文件夹 ${folderForm.value.name} 创建成功`);
      await refreshFiles();
    } else {
      emit('folder-create', {
        name: folderForm.value.name,
        path: currentPath.value
      });
    }
    
    createFolderDialogVisible.value = false;
  } catch (error) {
    console.error('创建文件夹失败:', error);
    ElMessage.error('创建文件夹失败，请重试');
  } finally {
    creatingFolder.value = false;
  }
};

// 显示上传文件对话框
const showUploadDialog = () => {
  uploadFiles.value = [];
  uploadDialogVisible.value = true;
};

// 处理文件选择
const handleFileChange = (file, fileList) => {
  uploadFiles.value = fileList;
};

// 上传选中的文件
const uploadSelectedFiles = async () => {
  if (!uploadFiles.value.length) {
    ElMessage.warning('请选择要上传的文件');
    return;
  }
  
  uploading.value = true;
  
  try {
    if (props.useCosService) {
      for (const file of uploadFiles.value) {
        await cosFileService.uploadFile(file.raw, currentPath.value);
      }
      ElMessage.success(`上传完成`);
      await refreshFiles();
    } else {
      emit('file-upload', {
        files: uploadFiles.value.map(f => f.raw),
        path: currentPath.value
      });
    }
    
    uploadDialogVisible.value = false;
  } catch (error) {
    console.error('上传文件失败:', error);
    ElMessage.error('上传文件失败，请重试');
  } finally {
    uploading.value = false;
  }
};

// 确认删除文件
const confirmDeleteFile = (file) => {
  ElMessageBox.confirm(
    `确定要删除${file.type === 'directory' ? '文件夹' : '文件'} ${file.name} 吗？`,
    '删除确认',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      if (props.useCosService) {
        await cosFileService.deleteFile(file.key);
        ElMessage.success(`删除成功`);
        await refreshFiles();
      } else {
        emit('file-delete', file);
      }
    } catch (error) {
      console.error('删除文件失败:', error);
      ElMessage.error('删除文件失败，请重试');
    }
  }).catch(() => {
    // 取消删除
  });
};

// 初始化COS服务
const initCosService = async () => {
  if (!props.useCosService) return false;
  
  try {
    console.log('正在初始化COS服务，配置:', props.cosConfig);
    const initialized = cosFileService.init(props.cosConfig);
    if (initialized) {
      console.log('COS服务初始化成功，路径前缀:', props.cosConfig.Prefix);
      return true;
    } else {
      console.error('初始化COS服务失败，无法获取文件列表');
      ElMessage.error('初始化COS服务失败');
      return false;
    }
  } catch (error) {
    console.error('初始化COS服务失败:', error);
    ElMessage.error('初始化COS服务失败: ' + (error.message || '未知错误'));
    return false;
  }
};

// 监听加载状态
watch(() => props.loading, (newVal) => {
  if (!props.useCosService) {
    internalLoading.value = newVal;
  }
});

// 组件挂载
onMounted(() => {
  if (props.useCosService) {
    initCosService().then(() => {
      // 成功初始化后自动加载文件列表
      loadFilesFromCos();
    });
  } else {
    internalFiles.value = props.files;
  }
});

// 处理高级搜索命令
const handleSearchCommand = (command) => {
  if (command === 'search-name') {
    // 聚焦到搜索框
    const searchInput = document.querySelector('.search-input input');
    if (searchInput) {
      searchInput.focus();
      ElMessage.info('请输入要搜索的文件名');
    }
  } else if (command === 'search-content') {
    // 内容搜索功能暂未实现
    ElMessage.warning('内容搜索功能即将推出，敬请期待');
  } else if (command === 'search-date') {
    // 日期搜索功能暂未实现
    ElMessage.warning('日期搜索功能即将推出，敬请期待');
  } else if (command === 'clear-search') {
    // 清除所有搜索条件
    searchQuery.value = '';
    categoryFilter.value = '';
    typeFilter.value = '';
    ElMessage.success('已清除所有搜索条件');
  }
};
</script>

<style scoped>
.file-explorer {
  @apply flex flex-col h-full;
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.explorer-header {
  padding: 16px;
  background-color: #f8fafc;
  border-bottom: 1px solid #e5e7eb;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.search-filter {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 16px;
}

.search-input {
  width: 240px;
  flex-grow: 1;
}

.filter-select {
  width: 160px;
}

.breadcrumb-nav {
  margin-bottom: 8px;
}

.breadcrumb-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.view-toggle {
  display: flex;
  align-items: center;
}

.view-radio :deep(.el-radio-button__inner) {
  display: flex;
  align-items: center;
  gap: 4px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.action-btn {
  transition: all 0.2s;
}

.explorer-body {
  flex: 1;
  overflow: auto; /* 保留自动滚动功能 */
  padding: 16px;
  position: relative;
}

/* 网格视图样式 */
.grid-view {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 16px;
  padding: 8px;
}

/* 加载状态 */
.loading-container {
  padding: 24px;
}

/* 预览对话框 */
.preview-dialog-content {
  height: 75vh;
}

/* 文件信息对话框 */
.file-info-content {
  padding: 8px;
}

.file-info-actions {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 上传区域 */
.upload-area {
  width: 100%;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .explorer-header {
    padding: 12px;
  }
  
  .action-bar {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .search-filter {
    flex-direction: column;
    align-items: stretch;
    width: 100%;
  }
  
  .search-input,
  .filter-select {
    width: 100%;
  }
  
  .grid-view {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
}

/* 空状态样式 */
.empty-state {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style> 